package paquete;
import java.io.IOException;
import java.util.Random;

import org.andengine.audio.music.Music;
import org.andengine.audio.music.MusicFactory;
import org.andengine.audio.sound.Sound;
import org.andengine.audio.sound.SoundFactory;
import org.andengine.engine.camera.Camera;
import org.andengine.engine.handler.runnable.RunnableHandler;
import org.andengine.engine.handler.timer.ITimerCallback;
import org.andengine.engine.handler.timer.TimerHandler;
import org.andengine.engine.options.EngineOptions;
import org.andengine.engine.options.ScreenOrientation;
import org.andengine.engine.options.WakeLockOptions;
import org.andengine.engine.options.resolutionpolicy.FillResolutionPolicy;
import org.andengine.entity.modifier.JumpModifier;
import org.andengine.entity.scene.IOnSceneTouchListener;
import org.andengine.entity.scene.Scene;
import org.andengine.entity.sprite.AnimatedSprite;
import org.andengine.entity.sprite.Sprite;
import org.andengine.entity.text.Text;
import org.andengine.input.touch.TouchEvent;
import org.andengine.opengl.font.Font;
import org.andengine.opengl.font.FontFactory;
import org.andengine.opengl.texture.ITexture;
import org.andengine.opengl.texture.TextureOptions;
import org.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas;
import org.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory;
import org.andengine.opengl.texture.region.ITextureRegion;
import org.andengine.opengl.texture.region.ITiledTextureRegion;
import org.andengine.ui.activity.SimpleBaseGameActivity;
import org.andengine.util.modifier.IModifier;
import org.andengine.util.modifier.ease.IEaseFunction;

import org.andengine.entity.IEntity;
import org.andengine.entity.modifier.IEntityModifier;
import org.andengine.entity.modifier.IEntityModifier.IEntityModifierListener;
import org.andengine.entity.modifier.IEntityModifier.IEntityModifierMatcher;
import org.andengine.entity.modifier.LoopEntityModifier;
import org.andengine.entity.modifier.ScaleModifier;
import org.andengine.entity.modifier.SequenceEntityModifier;

import android.graphics.Color;
import android.util.Log;

public class MainActivity extends SimpleBaseGameActivity implements IOnSceneTouchListener{
	private Scene sceneEjemplo;
	private Camera mCamera;
	private static int WIDTH = 1080;
	private static int HEIGHT = 720;

	private BitmapTextureAtlas atlasFondo;
	private ITextureRegion texturaFondo;
	private Sprite spriteFondo;

	private Font miFuente;
	private Text textChikenL;
	private Text textChikenR;
	private int cuentaL = 0;
	private int cuentaR = 0;
	private Sound miSonido;
	private Music miMusica;

	private float factorDeMovimiento = 50;
	//botones
	private BitmapTextureAtlas atlasChickenL;	
	private BitmapTextureAtlas atlasChickenR;	
	private ITiledTextureRegion texturaChickenL;
	private ITiledTextureRegion texturaChickenR;
	private AnimatedSprite spriteAnimadoChickenL;
	private AnimatedSprite spriteAnimadoChickenR;

	//
	private boolean isBotonSuspendidoL = false;
	private boolean isBotonSuspendidoR = false;

	//imagenes winner

	private BitmapTextureAtlas atlasWinnerR;	
	private BitmapTextureAtlas atlasWinnerL;	
	private ITextureRegion  texturaWinnerL;
	private ITextureRegion  texturaWinnerR;
	private  Sprite spriteWinnerL;
	private  Sprite spriteWinnerR;


	@Override
	public EngineOptions onCreateEngineOptions() {
		mCamera = new Camera(0, 0, WIDTH, HEIGHT);
		EngineOptions engineOptions = new EngineOptions(true, ScreenOrientation.LANDSCAPE_FIXED, new FillResolutionPolicy(), mCamera);
		engineOptions.setWakeLockOptions(WakeLockOptions.SCREEN_ON);
		engineOptions.getAudioOptions().setNeedsSound(true);
		engineOptions.getAudioOptions().setNeedsMusic(true);		
		return engineOptions;
	}
	@Override
	protected void onCreateResources() {		
		BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("imagenes/");

		//Fondo
		atlasFondo = new BitmapTextureAtlas(getTextureManager(), 1080, 720,TextureOptions.DEFAULT);			
		texturaFondo = BitmapTextureAtlasTextureRegionFactory.createFromAsset(atlasFondo, this, "farm.png", 0, 0);




		//Atlas Chiken
		atlasChickenL = new BitmapTextureAtlas(getTextureManager(), 1080, 720,TextureOptions.DEFAULT);
		atlasChickenR = new BitmapTextureAtlas(getTextureManager(), 1080, 720, TextureOptions.DEFAULT);


		//Textura Chiken
		texturaChickenL = BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(atlasChickenL, this, "chicken_L.png", 75, 0, 1, 3);
		texturaChickenR = BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(atlasChickenR, this, "chicken_R.png", 75, 0, 1, 3);


		atlasFondo.load();		
		//Load Chiken
		atlasChickenL.load();
		atlasChickenR.load();

		//Load Winner
		//Winner
		atlasWinnerR= new BitmapTextureAtlas(getTextureManager(), 1080, 720,TextureOptions.DEFAULT);	
		atlasWinnerL= new BitmapTextureAtlas(getTextureManager(), 1080, 720,TextureOptions.DEFAULT);

		texturaWinnerR = BitmapTextureAtlasTextureRegionFactory.createFromAsset(atlasWinnerR, this, "right_winner.png", 0, 0);
		texturaWinnerL = BitmapTextureAtlasTextureRegionFactory.createFromAsset(atlasWinnerL, this, "left_winner.png", 0, 0);

		atlasWinnerR.load();
		atlasWinnerL.load();		


		FontFactory.setAssetBasePath("fuentes/");
		final ITexture fontTexture = new BitmapTextureAtlas(getTextureManager(), 256, 256, TextureOptions.BILINEAR);
		miFuente = FontFactory.createFromAsset(getFontManager(), fontTexture, getAssets(), "HeeHawRegular.ttf", 45, true, Color.WHITE);
		miFuente.load();	
		try {			 
			miSonido = SoundFactory.createSoundFromAsset(getEngine().getSoundManager(), this, "sonido/chicken_scream.mp3");
			miSonido.setLooping(false);
			miSonido.setVolume(0.5f);
		} catch (IOException e) {
			// TODO: handle exception
			Log.e("Alejo", "IOException: Carga de audio");
		}		
		try {
			miMusica = MusicFactory.createMusicFromAsset(mEngine.getMusicManager(), this,"musica/chicken_battle.mp3");
			miMusica.setLooping(true);
		} catch (IOException e) {
			// TODO: handle exception
			Log.e("Alejo", "IOException: Carga de musica");
		}	
	}
	@Override
	protected Scene onCreateScene() {
		miMusica.setVolume(0.3f);
		miMusica.play();

		float posIni = 400f;
		sceneEjemplo = new Scene();		
		spriteFondo = new Sprite(WIDTH/2, HEIGHT/2, texturaFondo, getVertexBufferObjectManager());	

		spriteAnimadoChickenL = new AnimatedSprite(WIDTH/2 -posIni, HEIGHT/2, texturaChickenL, getVertexBufferObjectManager()){ 

			@Override
			public boolean onAreaTouched(TouchEvent pSceneTouchEvent,float pTouchAreaLocalX, float pTouchAreaLocalY) {            	

				if(isBotonSuspendidoL){

					Log.d("Alejo", " Gallina L ");                
					try {            		


						long[] duracionFrameL = { 100 };
						spriteAnimadoChickenL.animate(duracionFrameL, new int[]{2}, false);   

						spriteAnimadoChickenR.setVisible(false);
					} catch (IndexOutOfBoundsException  e) {
						// TODO: handle exception
						Log.i("Alejo", "sceneEjemplo.detachChild(this): "+e.getStackTrace());
					}                	
					cuentaL += 1;
				
					textChikenL.setText("Score: " + cuentaL + "/10");
					miSonido.play();

					isBotonSuspendidoL = false;
					isBotonSuspendidoR = false;
				}
				return super.onAreaTouched(pSceneTouchEvent, pTouchAreaLocalX, pTouchAreaLocalY);
			} 
		};


		spriteAnimadoChickenR = new AnimatedSprite(WIDTH/2 +posIni, HEIGHT/2, texturaChickenR, getVertexBufferObjectManager()){ 
			@Override
			public boolean onAreaTouched(TouchEvent pSceneTouchEvent,float pTouchAreaLocalX, float pTouchAreaLocalY) {

				if(isBotonSuspendidoR){
					Log.d("Alejo", " Gallina R ");            	 
					try {                		
						//remove(sceneEjemplo, spriteAnimadoChickenR);
						long[] duracionFrameR = { 100 };
						spriteAnimadoChickenR.animate(duracionFrameR, new int[]{2}, false);       
						spriteAnimadoChickenL.setVisible(false);

					} catch (IndexOutOfBoundsException  e) {
						// TODO: handle exception
						Log.i("Alejo", "sceneEjemplo.detachChild(this): "+e.getStackTrace());
					}                	
					cuentaR += 1;
					textChikenR.setText("Score: " + cuentaR + "/10");
					miSonido.play();                    

					isBotonSuspendidoL = false;
					isBotonSuspendidoR = false;
				}

				return super.onAreaTouched(pSceneTouchEvent, pTouchAreaLocalX, pTouchAreaLocalY);
			} 
		};		

		long[] duracionFrameL = { 100, 100 };
		spriteAnimadoChickenL.animate(duracionFrameL, 0, 1, true);


		long[] duracionFrameR = { 100, 100 };
		spriteAnimadoChickenR.animate(duracionFrameR, 0, 1, true);


		sceneEjemplo.attachChild(spriteFondo);		

		sceneEjemplo.registerTouchArea(spriteAnimadoChickenL);
		sceneEjemplo.attachChild(spriteAnimadoChickenL);

		sceneEjemplo.registerTouchArea(spriteAnimadoChickenR);
		sceneEjemplo.attachChild(spriteAnimadoChickenR);


		///TEXTO///////////////////////////////////
		//ok cuando cargamos una fuente, debemos cargar los caracteres	

		float separacionTexto = 50f;

		textChikenL = new Text(mCamera.getWidth()/2 - separacionTexto, mCamera.getHeight()/2 -separacionTexto*3, miFuente, "ScoreL:0123456789", getVertexBufferObjectManager());
		textChikenL.setText("Score: " + cuentaL + "/10");
		textChikenL.setRotation(90f);

		textChikenR = new Text(mCamera.getWidth()/2 + separacionTexto, mCamera.getHeight()/2 +separacionTexto*3, miFuente, "ScoreR:0123456789", getVertexBufferObjectManager());				
		textChikenR.setText("Score: " + cuentaR + "/10");				
		textChikenR.setRotation(-90f);

		sceneEjemplo.attachChild(textChikenR);
		sceneEjemplo.attachChild(textChikenL);

		///Evento de Listener////////////////////////////
		sceneEjemplo.setOnSceneTouchListener(this);	

		//posicion pollos
		
		spriteWinnerL = new Sprite(WIDTH/2, HEIGHT/2, texturaWinnerL, getVertexBufferObjectManager());
		spriteWinnerR = new Sprite(WIDTH/2, HEIGHT/2, texturaWinnerR, getVertexBufferObjectManager());
		
		spriteWinnerL.setVisible(false);
		spriteWinnerR.setVisible(false);
		
		
		createSpriteSpawnTimeHandler();
		
		
		
		sceneEjemplo.attachChild(spriteWinnerR);
		sceneEjemplo.attachChild(spriteWinnerL);
		
		
		return sceneEjemplo;
	}

	public void remove(final IEntity from, final IEntity entityToRemove) {
		runOnUpdateThread(new Runnable() {
			@Override
			public void run() {
				from.detachChild(entityToRemove);
			}
		});
	}

	@Override
	public boolean onSceneTouchEvent(Scene pScene, TouchEvent pSceneTouchEvent) {
		// TODO Auto-generated method stub		
		if(pSceneTouchEvent.isActionDown()){			
			//			cuenta++;
			//			miTexto.setText("Score: " + cuenta);
		}
		return false;
	}

	private void createSpriteSpawnTimeHandler() {
		TimerHandler spriteTimerHandler;
		float mEffectSpawnDelay = 1.5f;

		ITimerCallback hola =new ITimerCallback() {

			@Override
			public void onTimePassed(TimerHandler pTimerHandler) {
				
				if (!winner()) {
					moverPollo();
				}
			}
		};

		spriteTimerHandler = new TimerHandler(mEffectSpawnDelay, true,hola);
		getEngine().registerUpdateHandler(spriteTimerHandler);

	}

	public void moverPollo() {
		Random rand = new Random();

		//120 Y
		//90 X


		long[] duracionFrameR = { 100, 100 };
		long[] duracionFrameL = { 100, 100 };
		spriteAnimadoChickenL.animate(duracionFrameL, 0, 1, true);		
		spriteAnimadoChickenR.animate(duracionFrameR, 0, 1, true);

		float guardabanda = 140;
		float x = rand.nextInt((WIDTH/2)-90)+(WIDTH/2);
		if (x<WIDTH-guardabanda-100) {
			x+=guardabanda;
		}

		float y = rand.nextInt(HEIGHT-120);
		if (y<120) {
			y+= 120;
		}

		spriteAnimadoChickenR.setX(x);
		spriteAnimadoChickenR.setY(y);			

		spriteAnimadoChickenR.setVisible(true);
		isBotonSuspendidoR = true;


		x = rand.nextInt((WIDTH/2)-90);
		if (x>(WIDTH/2)-guardabanda-100) {
			x-=guardabanda;
		}

		y = rand.nextInt(HEIGHT-120);
		if (y<120) {
			y+= 120;
		}

		spriteAnimadoChickenL.setX(x);
		spriteAnimadoChickenL.setY(y);

		spriteAnimadoChickenL.setVisible(true);
		isBotonSuspendidoL = true;

	}


	public  boolean  winner(){	
		if(cuentaL>= 10){
			spriteWinnerL.setVisible(true);	
			spriteAnimadoChickenR.setVisible(false);
			spriteAnimadoChickenL.setVisible(false);
			return true;
		}

		if(cuentaR>= 10){
			spriteWinnerR.setVisible(true);
			spriteAnimadoChickenR.setVisible(false);
			spriteAnimadoChickenL.setVisible(false);
			return true;
		}
		return false;
	}


}
